﻿using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Umbrella.Whs.Service.Activities
{
    public abstract class SafeCodeActivity : CodeActivity
    {
        protected readonly log4net.ILog _log;

        protected sealed override void Execute(CodeActivityContext context)
        {
            try
            {
                if (context == null)
                    throw new ArgumentNullException("context");

                if (_log.IsDebugEnabled)
                    _log.Debug("Started activity in workflow #" + context.WorkflowInstanceId);

                ExecuteSafe(context);

                if (_log.IsDebugEnabled)
                    _log.Debug("Finished activity in workflow #" + context.WorkflowInstanceId);
            }
            catch (Exception x)
            {
                _log.Error("Activity failed in workflow #" + context.WorkflowInstanceId, x);

                throw;
            }
        }

        protected abstract void ExecuteSafe(CodeActivityContext context);

        protected SafeCodeActivity()
        {
            _log = log4net.LogManager.GetLogger(GetType());
        }
    }

    public abstract class SafeCodeActivity<T> : CodeActivity<T>
    {
        protected readonly log4net.ILog _log;

        protected sealed override T Execute(CodeActivityContext context)
        {
            try
            {
                if (context == null)
                    throw new ArgumentNullException("context");

                if (_log.IsDebugEnabled)
                    _log.Debug("Started activity in workflow #" + context.WorkflowInstanceId);

                var r = ExecuteSafe(context);

                if (_log.IsDebugEnabled)
                    _log.Debug("Finished activity in workflow #" + context.WorkflowInstanceId);

                return r;
            }
            catch (Exception x)
            {
                _log.Error("Activity failed in workflow #" + context.WorkflowInstanceId, x);

                throw;
            }
        }

        protected abstract T ExecuteSafe(CodeActivityContext context);

        protected SafeCodeActivity()
        {
            _log = log4net.LogManager.GetLogger(GetType());
        }
    }
}
